import React, {useEffect, useRef} from 'react';
import {createPortal} from 'react-dom';
import {X} from 'lucide-react';
import {IconButton} from '@/components/ui/Button';
import {cn} from '@/lib/utils';
import {ScrollContainer} from '@/components/ui/ScrollContainer';

interface ModalProps {
    open: boolean;
    onClose: () => void;
    title?: string;
    description?: string;
    footer?: React.ReactNode;
    showCloseButton?: boolean;
    closeOnBackdrop?: boolean;
    closeOnEscape?: boolean;
    size?: 'sm' | 'md' | 'lg' | 'xl';
    bodyScrollable?: boolean;
    className?: string;
    children?: React.ReactNode;
}

const sizeClasses = {
    sm: 'max-w-sm',
    md: 'max-w-lg',
    lg: 'max-w-2xl',
    xl: 'max-w-4xl',
};

export const Modal: React.FC<ModalProps> = ({
    open,
    onClose,
    title,
    description,
    footer,
    showCloseButton = true,
    closeOnBackdrop = true,
    closeOnEscape = true,
    size = 'md',
    bodyScrollable = true,
    children,
    className,
}) => {
    const backdropRef = useRef<HTMLDivElement>(null);
    const contentRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (!open || !closeOnEscape) return;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') onClose();
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [open, closeOnEscape, onClose]);

    useEffect(() => {
        if (!open) return;
        const prev = document.activeElement as HTMLElement;
        contentRef.current?.focus();
        return () => prev?.focus();
    }, [open]);

    const handleBackdropClick = (event: React.MouseEvent) => {
        if (closeOnBackdrop && event.target === backdropRef.current) onClose();
    };

    if (!open) return null;

    const modalContent = (
        <div
            ref={backdropRef}
            className="modal-backdrop"
            onClick={handleBackdropClick}
            role="dialog"
            aria-modal="true"
            aria-labelledby={title ? 'modal-title' : undefined}
            aria-describedby={description ? 'modal-description' : undefined}
        >
            <div
                ref={contentRef}
                // 说明：三行 Grid（头 auto / 体 1fr / 尾 auto）+ 视口自适应高度（clamp）
                className={cn(
                    'modal-content grid grid-rows-[auto_minmax(0,1fr)_auto] h-[85vh] min-h-[360px] max-h-[680px]',
                    sizeClasses[size],
                    className
                )}
                tabIndex={-1}
            >
                {/* 头部（固定） */}
                {(title || description || showCloseButton) && (
                    <div className="flex-shrink-0 flex items-start justify-between p-6 border-b border-gray-200">
                        <div className="flex-1 min-w-0">
                            {title && <h3 id="modal-title" className="text-lg font-semibold text-gray-900 mb-1">{title}</h3>}
                            {description && <p id="modal-description" className="text-sm text-gray-600">{description}</p>}
                        </div>
                        {showCloseButton && (
                            <IconButton
                                variant="ghost"
                                onClick={onClose}
                                className="ml-4 -mr-2 text-gray-400 hover:text-gray-600"
                                icon={<X size={20}/>}
                                aria-label="关闭模态框"
                            />
                        )}
                    </div>
                )}

                {/* 主体（可选滚动） */}
                {bodyScrollable ? (
                    // 说明：这一格允许被压缩；内部的 ScrollContainer 才是真正滚动者
                    <div className="min-h-0 px-6 py-6 overflow-hidden">
                        <ScrollContainer className="h-full" padRightForScrollbar={false}>
                            {children}
                        </ScrollContainer>
                    </div>
                ) : (
                    <div className="flex-1 min-h-0 px-6 py-6 overflow-visible">{children}</div>
                )}

                {/* 底部（固定） */}
                {footer && <div className="flex-shrink-0 p-6 border-t border-gray-200 bg-gray-50">{footer}</div>}
            </div>
        </div>
    );

    return createPortal(modalContent, document.body);
};

// 确认模态框组件
interface ConfirmModalProps {
    // 是否显示
    open: boolean;
    // 关闭回调
    onClose: () => void;
    // 确认回调
    onConfirm: () => void;
    // 标题
    title: string;
    // 内容
    message: string;
    // 确认按钮文本
    confirmText?: string;
    // 取消按钮文本
    cancelText?: string;
    // 确认按钮变体
    confirmVariant?: 'primary' | 'danger';
    // 是否正在加载
    loading?: boolean;
}

export const ConfirmModal: React.FC<ConfirmModalProps> = ({
    open,
    onClose,
    onConfirm,
    title,
    message,
    confirmText = '确认',
    cancelText = '取消',
    confirmVariant = 'primary',
    loading = false,
}) => {
    return (
        <Modal
            open={open}
            onClose={onClose}
            title={title}
            size="sm"
            className="h-auto min-h-0"
            bodyScrollable={false}
            closeOnBackdrop={!loading}
            closeOnEscape={!loading}
        >
            <div className="space-y-4">
                {/* 确认消息 */}
                <p className="text-sm text-gray-700">
                    {message}
                </p>

                {/* 操作按钮 */}
                <div className="flex justify-end gap-3">
                    <button
                        type="button"
                        className="btn-secondary"
                        onClick={onClose}
                        disabled={loading}
                    >
                        {cancelText}
                    </button>

                    <button
                        type="button"
                        className={confirmVariant === 'danger' ? 'btn-danger' : 'btn-primary'}
                        onClick={onConfirm}
                        disabled={loading}
                    >
                        {loading ? '处理中...' : confirmText}
                    </button>
                </div>
            </div>
        </Modal>
    );
};
